package com.lifang.framework.context.annotation;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ClassUtil;
import com.lifang.framework.beans.factory.config.BeanDefinitionRegistry;
import com.lifang.framework.beans.factory.support.BeanDefinition;
import com.lifang.framework.context.AnnotationParser;
import lombok.extern.slf4j.Slf4j;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Slf4j
public abstract class ClassPathScanningCandidateComponentProvider {

    protected abstract BeanDefinitionRegistry getRegistry();

    protected final Map<Class<? extends Annotation>, AnnotationParser> includeFilters = new HashMap<>();

    public Set<Class<?>> findCandidate(String basePackage) {
        return ClassUtil.scanPackage(basePackage);
    }

    public void registerBeanDefinition(String basePackage) {
        Set<Class<?>> candidate = findCandidate(basePackage);
        if (CollectionUtil.isNotEmpty(candidate)) {
            for (Class<?> aClass : candidate) {
                for (Map.Entry<Class<? extends Annotation>, AnnotationParser> entry : includeFilters.entrySet()) {
                    if (aClass.isAnnotationPresent(entry.getKey())) {
                        BeanDefinition definition = entry.getValue().parser(aClass);
                        getRegistry().registerBeanDefinition(definition.getBeanClassName(), definition);
                    }
                }
            }
        }
    }
}
